//
//  SearchViewController.m
//  SmileRead
//
//  Created by dllo on 15/8/29.
//  Copyright (c) 2015年 JIZ. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchView.h"
#import "VoiceCell.h"
#import "ReadCell.h"
#import "VoiceModel.h"
#import "ReadModel.h"
#import "VoiceSecondViewController.h"
#import "ReadSecondViewController.h"
#import "AppDelegate.h"
#import "Path.h"

@interface SearchViewController ()<UITableViewDataSource, UITableViewDelegate,SearchViewDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSArray *arrayOfdata;
@property (nonatomic, retain) NSString *text;
@property (nonatomic, retain) NSMutableArray *currentArr;
@property (nonatomic, retain) NSString *ident;

@end

@implementation SearchViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arrayOfdata = [NSArray array];
        self.currentArr = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc
{
    [_ident release];
    [_arrayOfdata release];
    [_text release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"搜索";
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createTableView];
    
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    [Path separatorStyleWithTableview:self.tableView array:self.currentArr];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    //self.tableView.backgroundColor = [Path colorWithRed:175 green:175 blue:175];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    SearchView *search = [[[SearchView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45 * heightFit)] autorelease];
    search.delegate = self;
    search.target = self;
    search.action = @selector(search:);
    self.tableView.tableHeaderView = search;
}

// 接收数据
- (void)receiveArray:(NSArray *)array ident:(NSString *)ident
{
    self.arrayOfdata = array;
    self.ident = ident;
}

- (void)sendWithTextWhenDidChange:(NSString *)text{
    self.text = text;
    NSLog(@"%@", text);
    
}

- (void)seach
{
    // 进行筛选, 先删除原有数据
    [self.currentArr removeAllObjects];
    NSPredicate *perdicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@",self.text];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 将数据数组的modle的title装到数组中
        NSMutableArray *array = [NSMutableArray array];
        if ([self.ident isEqualToString:@"music"]) {
            for (VoiceModel *model in self.arrayOfdata) {
                [array addObject:model.title];
            }
            
            NSArray *arr = [array filteredArrayUsingPredicate:perdicate];
            for (VoiceModel *model in self.arrayOfdata) {
                for (NSString *title in arr) {
                    if ([title isEqualToString:model.title]) {
                        [self.currentArr addObject:model];
                    }
                }
            }
        }
        
        if ([self.ident isEqualToString:@"read"]) {
            for (ReadModel *model in self.arrayOfdata) {
                [array addObject:model.title];
            }
            
            NSArray *arr = [array filteredArrayUsingPredicate:perdicate];
            for (ReadModel *model in self.arrayOfdata) {
                for (NSString *title in arr) {
                    if ([title isEqualToString:model.title]) {
                        [self.currentArr addObject:model];
                    }
                }
            }
        }
        // 回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.tableView reloadData];
            
            if (self.currentArr.count == 0) {
                self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"搜索" message:@"没有您搜索的结果" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *acrion = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    
                }];
                [alert addAction:acrion];
                AppDelegate *tempAppDelegate = [[UIApplication sharedApplication] delegate];
                [tempAppDelegate.window.rootViewController presentViewController:alert animated:YES completion:^{
                    
                }];
            }
            else {
                self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
            }
        });
    });

}

// 点击进行筛选
- (void)search:(UITextField *)tf
{
    [self.view endEditing:NO];
    self.text = tf.text;
    [self seach];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.currentArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identOfMusic = @"music";
    static NSString *identOfRead = @"read";
    if ([self.ident isEqualToString:@"music"]) {
        VoiceCell *cell = [tableView dequeueReusableCellWithIdentifier:identOfMusic];
        if (cell == nil) {
            cell = [[[VoiceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identOfMusic] autorelease];
        }
        
        VoiceModel *model = self.currentArr[indexPath.row];
        cell.model = model;
        [cell receiveWithModel:model text:self.text];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        
        return cell;
    }
    
    else {
        ReadCell *cell = [tableView dequeueReusableCellWithIdentifier:identOfRead];
        if (cell == nil) {
            cell = [[[ReadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identOfRead] autorelease];
        }
        ReadModel *model = self.currentArr[indexPath.row];
        cell.model = model;
        [cell receiveWithModel:model text:self.text];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.ident isEqualToString:@"music"]) {
        VoiceSecondViewController *second = [[VoiceSecondViewController alloc] init];
        VoiceModel *model = self.currentArr[indexPath.row];
        [second receiveWithModel:model];
        [self.navigationController pushViewController:second animated:YES];
        [second release];
    }
    
    else {
        ReadSecondViewController *second = [[ReadSecondViewController alloc] init];
        ReadModel *model = self.currentArr[indexPath.row];
        
        [second receivewithModel:model];
        
        AppDelegate *tempAppdelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [tempAppdelegate.window.rootViewController presentViewController:second animated:YES completion:^{
            
        }];
        [second release];

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.ident isEqualToString:@"music"]) {
        return 180 * heightFit;
    }
    else {
        return 150 * heightFit;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
